<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div class="profile-header">
        <div class="header-left">
          <el-button
              type="primary"
              @click="goToHome"
              class="home-button"
          >
            <el-icon><House /></el-icon>
            <span>返回首页</span>
          </el-button>
          <h2>个人中心</h2>
        </div>
        <el-button
            type="primary"
            @click="editMode = true"
            v-if="!editMode"
            class="edit-button"
        >
          <el-icon><Edit /></el-icon>
          <span>修改个人信息</span>
        </el-button>
      </div>

      <div class="profile-content">
        <div v-if="!editMode" class="profile-details">
          <el-descriptions :column="1" border class="descriptions-container">
            <el-descriptions-item label="头像" class="avatar-item">
              <el-avatar :size="150" :src="userInfo.avatarImg || defaultAvatar" />
            </el-descriptions-item>
            <el-descriptions-item label="用户ID">
              <span class="highlight">{{ userInfo.userId }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="用户名">
              <span class="highlight">{{ userInfo.username }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="手机号">
              <span class="highlight">{{ userInfo.mobite }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="年龄">
              <span class="highlight">{{ userInfo.age }}</span> 岁
            </el-descriptions-item>
            <el-descriptions-item label="账户余额">
              <span class="balance">¥ {{ userInfo.balance.toFixed(2) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ formatDate(userInfo.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="最后更新时间">{{ formatDate(userInfo.updateTime) }}</el-descriptions-item>
          </el-descriptions>

          <div class="profile-stats">
            <div class="stat-item">
              <div class="stat-value">128</div>
              <div class="stat-label">订单总数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">36</div>
              <div class="stat-label">收藏商品</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">12</div>
              <div class="stat-label">优惠券</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">98%</div>
              <div class="stat-label">完成率</div>
            </div>
          </div>
        </div>

        <UserForm
            v-else
            :user-data="userInfo"
            @submit="updateProfile"
            @cancel="editMode = false"
        />
      </div>

      <div class="card-footer">
        © {{ new Date().getFullYear() }} 个人中心 | 最后登录时间: {{ formatDate(userInfo.lastLogin) }}
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { House, Edit } from '@element-plus/icons-vue';
import { useAuthStore } from '@/store/auth';
import userService from '@/services/user';
import UserForm from './UserForm.vue';

const router = useRouter();
const authStore = useAuthStore();
const editMode = ref(false);
const userInfo = ref({
  userId: '',
  username: '',
  mobite: '',
  age: 18,
  avatarImg: '',
  balance: 0,
  createTime: '',
  updateTime: '',
  lastLogin: new Date().toISOString()
});

const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 返回首页
const goToHome = () => {
  router.push('/');
};

// 获取用户信息
const fetchUserProfile = async () => {
  try {
    const response = await userService.getUserProfile();
    if (response.code === 200) {
      userInfo.value = response.data;
    } else {
      ElMessage.error(response.message || '获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// 更新用户信息 - 关键修改
const updateProfile = async (formData) => {
  try {
    // 发送FormData到后端
    const response = await userService.updateUserProfile(formData);

    if (response.code === 200) {
      ElMessage.success('个人信息更新成功');

      // 更新本地存储的用户信息
      authStore.setUser({
        ...authStore.user,
        age: formData.get('age'),
        // 头像更新需要根据后端返回处理
        avatarImg: response.data.avatarUrl || authStore.user.avatarImg
      });

      fetchUserProfile(); // 重新获取最新数据
      editMode.value = false;
    } else {
      ElMessage.error(response.message || '更新失败');
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

onMounted(() => {
  fetchUserProfile();
});
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 40px auto;
  padding: 20px;
}

.profile-card {
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 35px;
  background-color: #fff;
  position: relative;
  overflow: hidden;
}

.profile-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 8px;
  background: linear-gradient(90deg, #409eff, #e54847);
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 25px;
  border-bottom: 1px solid #ebeef5;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 25px;
}

.home-button {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  border: none;
  padding: 12px 22px;
  font-size: 15px;
  border-radius: 8px;
  color: white;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.home-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(64, 158, 255, 0.4);
}

.profile-content {
  padding: 20px;
}

.profile-details {
  margin-top: 20px;
  animation: fadeIn 0.6s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.descriptions-container {
  width: 100%;
  font-size: 16px;
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-descriptions__label) {
  width: 150px;
  font-weight: bold;
  color: #606266;
  background-color: #f8fafc;
  padding-left: 25px !important;
}

:deep(.el-descriptions__content) {
  padding-left: 35px !important;
  color: #303133;
  font-size: 16px;
}

.avatar-item :deep(.el-descriptions__content) {
  padding: 25px 0 25px 35px !important;
}

.balance {
  color: #e54847;
  font-weight: bold;
  font-size: 24px;
  position: relative;
  display: inline-block;
}

.balance::after {
  content: "";
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 100%;
  height: 3px;
  background: linear-gradient(90deg, #e54847, #ff9e7d);
  border-radius: 3px;
}

.edit-button {
  padding: 13px 32px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(135deg, #e54847, #ff7e7e);
  border: none;
  color: white;
  box-shadow: 0 4px 12px rgba(229, 72, 71, 0.3);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.edit-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(229, 72, 71, 0.4);
}

h2 {
  font-size: 28px;
  color: #303133;
  margin: 0;
  font-weight: 600;
  position: relative;
  padding-left: 15px;
}

h2::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 28px;
  background: #409eff;
  border-radius: 3px;
}

.card-footer {
  margin-top: 30px;
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.profile-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 30px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
}

.stat-item {
  text-align: center;
  padding: 15px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.highlight {
  background: linear-gradient(90deg, #409eff, #e54847);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-weight: 500;
}
</style>